package com.mk.controller.user;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.mk.constant.JwtClaimsConstant;
import com.mk.constant.RedisCacheConstant;
import com.mk.context.BaseContext;
import com.mk.dto.UserLoginDTO;
import com.mk.entity.User;
import com.mk.properties.JwtProperties;
import com.mk.result.Result;
import com.mk.service.IUserService;
import com.mk.utils.JwtUtil;
import com.mk.utils.RedisUtil;
import com.mk.vo.UserLoginVO;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.Builder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
@RequiredArgsConstructor
public class UserController {

    private final IUserService userService;

    private final RedisTemplate<String, String> redisTemplate;

    @Resource
    private JwtProperties jwtProperties;

    private final JwtUtil jwtUtil;

//    //延迟初始化JwtUtil
//    @PostConstruct
//    public void init() {
//        this.jwtUtil = new JwtUtil(jwtProperties.getUserSecretKey());
//    }

    /*@CrossOrigin
    @PostMapping("/login")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("微信用户登录: {}", userLoginDTO.getCode());
        //微信登录
        User user = userService.wxLogin(userLoginDTO);
        //为微信用户生成JWT令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtils.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build();
        return Result.success(userLoginVO);
    }
*/
    /**
     * 用户注册
     * @param userLoginDTO
     * @return
     */
    @CrossOrigin
    @PostMapping("/register")
    public Result register(@RequestBody UserLoginDTO userLoginDTO) {
        userService.register(userLoginDTO);
        return Result.success();
    }

    /**
     * 用户更新相关信息
     * @param user
     * @return
     */
    @CrossOrigin
    @PutMapping("/update/info")
    public Result updateInfo(@RequestBody User user) {
        user.setId(BaseContext.getCurrentId());
        userService.updateById(user);
        return Result.success();
    }


    /**
     * 账号密码登录
     * @param userLoginDTO
     * @return
     */
    @CrossOrigin
    @PostMapping("/login/password")
    public Result<UserLoginVO> loginByPassword(@RequestBody UserLoginDTO userLoginDTO) {
        User user = userService.login(userLoginDTO);

        //登录成功后，生成jwt令牌
//        Map<String, Object> claims = new HashMap<>();
//        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        RedisUtil redisUtil = new RedisUtil(redisTemplate);
        String token = String.valueOf(redisUtil.get(RedisCacheConstant.USER_LOGIN_KEY + user.getUsername()));
        if (token == null || token.isEmpty() || "null".equals(token)) {
            token = jwtUtil.generateToken(user.getUsername(), jwtProperties.getTtl());
            redisUtil.set(RedisCacheConstant.USER_LOGIN_KEY + user.getUsername(), token, jwtProperties.getTtl());
        } else {
            if (!jwtUtil.validateToken(token, user.getUsername())) {
                token = jwtUtil.refreshToken(token);
                redisUtil.set(RedisCacheConstant.USER_LOGIN_KEY + user.getUsername(), token, jwtProperties.getTtl());
            }
        }


        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .token(token)
                .build();

        return Result.success(userLoginVO);
    }

    /**
     * 退出
     * @return
     */
    @CrossOrigin
    @PostMapping("/logout")
    public Result<String> logout() {
        Long id = BaseContext.getCurrentId();
        userService.update(new LambdaUpdateWrapper<User>()
                .set(User::getStatus, User.NOT_ONLINE)
                .set(User::getOfflineTime, LocalDateTime.now())
                .eq(User::getId, id));
        return Result.success();
    }

    /**
     * 微信手机号一键登录
     * @param userLoginDTO
     * @return
     * @throws IOException
     */
    /*@CrossOrigin
    @PostMapping("/login/phone")
    public Result<UserLoginVO> loginByPhone(@RequestBody UserLoginDTO userLoginDTO) throws IOException {
        //微信登录
        User user = userService.wxLoginByPhone(userLoginDTO);
        //为微信用户生成JWT令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtils.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build();
        return Result.success(userLoginVO);
    }*/

    //TODO 手机号验证短信登录


    //TODO QQ授权登录
}
